package com.example.myapp.note;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;

import androidx.annotation.Nullable;

import com.example.myapp.note.NoteBean;

import java.util.ArrayList;
import java.util.List;

public class SQLiteHelper  extends SQLiteOpenHelper {
    private SQLiteDatabase db;
    private Context ctx;

    public SQLiteHelper(@Nullable Context context) {
        super(context, DBUtils.DATABASE_NAME, null, DBUtils.DATABASE_VERSION);
        db = this.getWritableDatabase();
        ctx = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE " + DBUtils.DATABASE_TABLE +
                "(id INTEGER PRIMARY KEY AUTOINCREMENT, content TEXT, time TEXT)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
    public boolean insertData(String content, String time) {
        ContentValues contentValues = new ContentValues();
        contentValues.put("content", content);
        contentValues.put("time", time);
        boolean result = db.insert(DBUtils.DATABASE_TABLE, null, contentValues) > 0;
        if (result) {
            Uri uri = Uri.parse("content://com.example.myapp.test");
            ctx.getContentResolver().notifyChange(uri, null);
        }
        return result;
    }
    public boolean deleteData(String id) {
        return db.delete(DBUtils.DATABASE_TABLE, "id=?", new String[]{id}) > 0;
    }
    public boolean updateData(String id, String content, String time) {
        ContentValues contentValues = new ContentValues();
        contentValues.put("content", content);
        contentValues.put("time", time);
        return db.update(
                DBUtils.DATABASE_TABLE, contentValues, "id=?", new String[]{id}) > 0;
    }
    public List<NoteBean> query() {
        List<NoteBean> list = new ArrayList<NoteBean>();
        Cursor cursor = db.query(
                DBUtils.DATABASE_TABLE, null, null, null,
                null, null, "id DESC");
        if (cursor != null) {
            while (cursor.moveToNext()) {
                NoteBean noteBean = new NoteBean();
                String id = String.valueOf(cursor.getInt(cursor.getColumnIndex("id")));
                String content = cursor.getString(cursor.getColumnIndex("content"));
                String time = cursor.getString(cursor.getColumnIndex("time"));
                noteBean.setId(id);
                noteBean.setContent(content);
                noteBean.setTime(time);
                list.add(noteBean);
            }
            cursor.close();
        }
        return list;
    }
}
